"""
状态监控模型，用于集中管理各种状态信息
"""
from typing import Dict, Any, List, Callable, Optional
from app.utils.logger import Logger

class StatusType:
    """状态类型常量"""
    CONNECTION = "connection"
    AUDIO_SERVICE = "audio_service"
    AI_SERVICE = "ai_service"
    SYNC = "sync"
    KEYWORD = "keyword"
    USER_JOIN = "user_join"
    AUDIO_OUTPUT = "audio_output"
    PLAYBACK = "playback"

class StatusMonitorModel:
    """
    状态监控数据模型，管理所有状态数据和变更通知
    """
    _instance = None
    
    @classmethod
    def instance(cls):
        """
        获取单例实例
        
        @return: 状态监控模型实例
        """
        try:
            if cls._instance is None:
                cls._instance = StatusMonitorModel()
            return cls._instance
        except Exception as e:
            # 出现异常时记录错误并创建一个基本实例
            logger = Logger.get_logger("status_monitor")
            logger.error(f"创建状态监控模型实例失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            
            # 防止重复创建导致的无限递归
            if not hasattr(cls, "_error_instance"):
                cls._error_instance = object.__new__(cls)
                cls._error_instance.logger = logger
                cls._error_instance._states = {}
                cls._error_instance._listeners = {}
                cls._error_instance._last_ai_status = "未启用"
            return cls._error_instance
    
    def __init__(self):
        """初始化状态监控模型"""
        # 防止重复初始化
        if StatusMonitorModel._instance is not None:
            return
            
        # 获取日志记录器
        self.logger = Logger.get_logger("status_monitor")
        
        # 状态数据存储
        self._states: Dict[str, Any] = {}
        
        # 状态更新监听器
        self._listeners: Dict[str, List[Callable]] = {}
        
        # 初始化基本状态项
        self._initialize_states()
        
        # AI服务状态缓存
        self._last_ai_status = "未连接"
        
        self.logger.info("状态监控模型初始化完成")
    
    def _initialize_states(self):
        """初始化所有状态项"""
        self._states = {
            StatusType.CONNECTION: "未连接",
            StatusType.AUDIO_SERVICE: "未连接",
            StatusType.AI_SERVICE: "未连接",
            StatusType.SYNC: "未开启",
            StatusType.KEYWORD: "未配置",
            StatusType.USER_JOIN: "未配置",
            StatusType.AUDIO_OUTPUT: "默认设备",
            StatusType.PLAYBACK: "停止"
        }
    
    def get_state(self, state_type: str) -> Any:
        """
        获取指定类型的状态值
        
        @param state_type: 状态类型
        @return: 状态值
        """
        try:
            return self._states.get(state_type)
        except Exception as e:
            self.logger.error(f"获取状态值失败: {str(e)}")
            return None
    
    def update_state(self, state_type: str, value: Any) -> None:
        """
        更新状态并通知监听器
        
        @param state_type: 状态类型
        @param value: 状态值
        """
        try:
            # 特殊处理AI服务状态
            if state_type == StatusType.AI_SERVICE:
                # 确保AI服务状态只能是"已连接"或"未连接"
                if value not in ["已连接", "未连接"]:
                    self.logger.warning(f"收到非法AI服务状态: {value}，强制转换为'未连接'")
                    value = "未连接"
                    
                # 保存最新AI服务状态
                self._last_ai_status = value
            
            # 检查状态是否发生变化
            if state_type in self._states and self._states[state_type] == value:
                self.logger.debug(f"状态未变化，跳过更新: {state_type}={value}")
                return
            
            # 更新状态
            old_value = self._states.get(state_type)
            self._states[state_type] = value
            self.logger.debug(f"状态已更新: {state_type}={value} (原值: {old_value})")
            
            # 通知监听器
            self._notify_listeners(state_type, value)
        except Exception as e:
            self.logger.error(f"更新状态失败: {str(e)}")
            import traceback
            self.logger.error(traceback.format_exc())
    
    def add_listener(self, state_type: str, listener: Callable) -> None:
        """
        添加状态变更监听器
        
        @param state_type: 状态类型
        @param listener: 监听器回调函数
        """
        try:
            if state_type not in self._listeners:
                self._listeners[state_type] = []
            
            if listener not in self._listeners[state_type]:
                self._listeners[state_type].append(listener)
                self.logger.debug(f"已添加监听器: {state_type}")
        except Exception as e:
            self.logger.error(f"添加监听器失败: {str(e)}")
    
    def remove_listener(self, state_type: str, listener: Callable) -> None:
        """
        移除状态变更监听器
        
        @param state_type: 状态类型
        @param listener: 监听器回调函数
        """
        try:
            if state_type in self._listeners and listener in self._listeners[state_type]:
                self._listeners[state_type].remove(listener)
                self.logger.debug(f"已移除监听器: {state_type}")
        except Exception as e:
            self.logger.error(f"移除监听器失败: {str(e)}")
    
    def _notify_listeners(self, state_type: str, value: Any) -> None:
        """
        通知指定类型的所有监听器
        
        @param state_type: 状态类型
        @param value: 状态值
        """
        try:
            if state_type in self._listeners:
                for listener in self._listeners[state_type]:
                    try:
                        listener(value)
                    except Exception as e:
                        self.logger.error(f"调用监听器异常: {str(e)}")
        except Exception as e:
            self.logger.error(f"通知监听器失败: {str(e)}")
    
    def get_last_ai_status(self) -> str:
        """
        获取最近保存的AI服务状态
        
        @return: AI服务状态
        """
        try:
            # 直接从状态字典中获取当前AI服务状态
            return self._states.get(StatusType.AI_SERVICE, "未连接")
        except Exception as e:
            self.logger.error(f"获取AI服务状态失败: {str(e)}")
            return "未连接" 